package demo;

import java.io.IOException;

import net.sf.ehcache.CacheException;

import org.apache.log4j.Logger;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class CachingConfig implements CachingConfigurer {

    private static final Logger LOGGER = Logger.getLogger(CachingConfig.class);

    @Bean(destroyMethod = "shutdown")
    public net.sf.ehcache.CacheManager ehCacheManager() {
        // final CacheConfiguration cacheConfiguration = new
        // CacheConfiguration();
        // cacheConfiguration.setName("users");
        // cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");
        // cacheConfiguration.setMaxEntriesLocalHeap(1000);
        //
        // final net.sf.ehcache.config.Configuration config = new
        // net.sf.ehcache.config.Configuration();
        // config.addCache(cacheConfiguration);
        //
        net.sf.ehcache.CacheManager ehCacheManager = null;
        try {
            ehCacheManager = net.sf.ehcache.CacheManager.create(new ClassPathResource("ehcache.xml").getInputStream());
        } catch (CacheException | IOException e) {
            LOGGER.error(e.getMessage(), e);
            throw new IllegalArgumentException(e);
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Return ehCacheManager from ehcache.xml");
        }
        return ehCacheManager;
    }

    @Bean
    @Override
    public CacheManager cacheManager() {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Return Spring EhCache CacheManager");
        }
        return new EhCacheCacheManager(ehCacheManager());
    }

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new SimpleKeyGenerator();
    }
}
